package api

import (
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"log"
	"net/http"
	"strconv"
	"z-blog/e"
	"z-blog/models"
)

func GetArticleByTag(c *gin.Context) {
	maps := make(map[string]interface{})
	data := make(map[string]interface{})

	tagId := c.Query("tag_id")
	code := e.SUCCESS

	maps["tag_id"] = tagId
	data["list"] = models.SelectArticle(maps)

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}

func GetArticleByTagBasic(c *gin.Context) {
	maps := make(map[string]interface{})
	data := make(map[string]interface{})

	tagId := c.Query("tag_id")
	code := e.SUCCESS

	maps["tag_id"] = tagId
	data["list"] = models.SelectArticleBasic(maps)

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}

func GetArticleById(c *gin.Context) {
	maps := make(map[string]interface{})
	data := make(map[string]interface{})

	id := c.Query("id")
	code := e.SUCCESS

	maps["id"] = id
	data["list"] = models.SelectArticle(maps)

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}

func AddArticle(c *gin.Context) {
	maps := make(map[string]interface{})
	data := make(map[string]interface{})
	code := e.SUCCESS
	var fileContent string

	f, err := c.FormFile("file")
	if err != nil {
		code = e.ERROR
	} else {
		log.Println(f.Filename)
		file, _ := f.Open()
		defer file.Close()

		msg, _ := ioutil.ReadAll(file)
		fileContent = string(msg)
	}

	maps["TagId"], _ = strconv.Atoi(c.PostForm("tag_id"))
	maps["Name"] = c.PostForm("name")
	maps["Content"] = fileContent
	maps["CreatedBy"] = c.PostForm("created_by")
	maps["Time"] = c.PostForm("time")
	maps["Thumbs"] = 0

	data["list"] = models.InsertArticle(maps)

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}

func DelArticle(c *gin.Context) {
	maps := make(map[string]interface{})
	code := e.SUCCESS

	maps["Id"] = c.Query("id")

	if models.DelArticle(maps) != nil {
		code = e.ERROR
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": nil,
	})
}

func ThumbsUp(c *gin.Context) {
	maps := make(map[string]interface{})
	code := e.SUCCESS

	maps["Id"] = c.Query("id")

	if models.AddThumbs(maps) != nil {
		code = e.ERROR
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": nil,
	})
}
